/**
 *  编辑页
 *
 * 作者 admin
 * 日期 2024-08-07 16:43:01
 */
layui.use(['jquery','febs', 'form', 'validate','upload','fileUpload'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        laydate = layui.laydate,
        form = layui.form,
        fileUpload = layui.fileUpload,
        commonJs = layui.commonJS,
        $view = $('#accidentReport-edit'),
        $noticeDeptFlg = $view.find('#noticeDeptFlg'),
        // $casualtyFlg = $view.find('#casualtyFlg'),
        $acceptAssistFlg = $view.find('#acceptAssistFlg'),
        $accidentType = $view.find('#accidentType'),
        $accidentLevel = $view.find('#accidentLevel'),
        $jobOperation = $view.find('#jobOperation'),
        $accidentShipType = $view.find('#accidentShipType'),
        // $deptSelect = $('#deptSelect'),
        // $deptTeamSelect = $('#deptTeamSelect'),
        // $correlationUserSelect = $('#correlationUserSelect'),
        validate = layui.validate;
    let tenantId = POPUP_DATA.tenantId;
    let accidentReportFileList = [];

    //初始化select
    initDictItemSelect_edit();
    // initAccidentAreaId();

    form.verify(validate);
    form.render();
    initFormValue();

    laydate.render({
        elem: "#accidentDate",
        done: function (value, date) {},
        type: 'datetime'
    })

    laydate.render({
        elem: "#surveyDeadLine",
        done: function (value, date) {},
        type: 'date'
    })

    laydate.render({
        elem: "#noticeDeptDate",
        done: function (value, date) {},
    })

    fileUpload.render({
        elem:'#uploadBtn',
        url:ctx + 'accident/upload',
        type:'2',
        maxNum:5,
        defaultData: accidentReportData && accidentReportData.accidentReportFileList ? accidentReportData.accidentReportFileList:[],
        done:function(res){
        }
        ,error: function(){
            layer.msg("服务器异常")
        }
    })

    // 新增时删除文件
    window.deleteFile = function (_this) {
        let id = `item${$(_this).attr('id')}`;
        $('#'+`${id}`).remove();
        $("#showFiles").empty();
        $("#uploadBtn").show();
    }

    function initDictItemSelect_edit(){
        //事故类型
        febs.initDictItemSelect($accidentType,'SAFETY_ACCIDENT_TYPE',accidentReportData.accidentType,null);
        //事故等级
        febs.initDictItemSelect($accidentLevel,'SAFETY_ACCIDENT_LEVEL',accidentReportData.accidentLevel,null);
        //作业类别
        // febs.initDictItemSelect($jobOperation,'SAFETY_JOB_OPERATION',accidentReportData.jobOperation,null);

        //船舶类型
        febs.initDictItemSelect($accidentShipType,'SAFETY_SHIP_TYPE',accidentReportData.accidentShipType,null);

    }

    // //所属科室点击事件
    // $deptSelect.on('click', function () {
    //     febs.modal.open('所属科室选择', 'common/dept', {
    //         btn: ['确认','关闭'],
    //         area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
    //         data:{
    //             tenantId:tenantId,
    //             deptType:'3',
    //             multiple:false,
    //         },
    //         yes: function (index, layero) {
    //             let selectData = null
    //             if(typeof getSelectData  === 'function'){
    //                 selectData = getSelectData()
    //             }
    //             $view.find("input[name=deptId]").val(selectData.deptId);
    //             $view.find("input[name=deptName]").val(selectData.deptName);
    //             layer.close(index);
    //         },
    //         btn2: function (index, layero) {
    //             layer.close(index);
    //             return false;
    //         }
    //     });
    // });
    //
    // //所属班组点击事件
    // $deptTeamSelect.on('click', function () {
    //     var deptId = $view.find("input[name=deptId]").val();
    //     if(commonJs.isEmpty(deptId)){
    //         febs.alert.warn('请选择所属科室');
    //         return false;
    //     }
    //     febs.modal.open('所属班组选择', 'common/dept', {
    //         btn: ['确认','关闭'],
    //         area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
    //         data:{
    //             tenantId:tenantId,
    //             deptType:'5',
    //             multiple:false,
    //         },
    //         yes: function (index, layero) {
    //             let selectData = null
    //             if(typeof getSelectData  === 'function'){
    //                 selectData = getSelectData()
    //             }
    //             $view.find("input[name=deptTeamId]").val(selectData.deptId);
    //             $view.find("input[name=deptTeamName]").val(selectData.deptName);
    //             layer.close(index);
    //         },
    //         btn2: function (index, layero) {
    //             layer.close(index);
    //             return false;
    //         }
    //     });
    // });
    //
    // //相关人员点击事件
    // $correlationUserSelect.on('click', function () {
    //     var deptTeamId = $view.find("input[name=deptTeamId]").val();
    //     if(commonJs.isEmpty(deptTeamId)){
    //         febs.alert.warn('请选择所属班组');
    //         return false;
    //     }
    //     febs.modal.open('相关人员选择', 'common/user', {
    //         btn: ['确认','关闭'],
    //         area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
    //         data:{
    //             tenantId:tenantId,
    //             deptId:deptTeamId,
    //             // parentId:deptId,
    //             multiple:true,
    //         },
    //         yes: function (index, layero) {
    //             let selectData = null
    //             if(typeof getSelectData  === 'function'){
    //                 selectData = getSelectData()
    //             }
    //             let unameList = [];
    //             if(selectData){
    //                 let data = getSelectData()
    //                 let htl = ``;
    //                 if (data && data.length > 0) {
    //                     data.forEach((item, index) => {
    //                         unameList.push(item.uname);
    //                         htl += `<span name="correlation" class="tag" data-id="${item.userId}" data-name="${item.uname}(${item.userNo})">${item.uname}(${item.userNo})<span style="color: red;margin-left: 5px;cursor:pointer;" onclick="delTags(this)">x</span></span>`
    //                     })
    //                 } else {
    //                     htl += `<span name="correlation" class="tag" data-id="${data.userId}" data-name="${data.uname}(${data.userNo})">${data.uname}(${data.userNo})<span style="color: red;margin-left: 5px;cursor:pointer;" onclick="delTags(this)">x</span></span>`
    //                 }
    //                 $('.selectName').html(htl)
    //                 $view.find("input[name=correlationUser]").val(unameList.join(','));
    //                 layer.close(index);
    //             }
    //             layer.close(index);
    //         },
    //         btn2: function (index, layero) {
    //             layer.close(index);
    //             return false;
    //         }
    //     });
    // });

    window.delTags = function (data) {
        $(data).parent().remove()
    }
    function initFormValue() {
        if (accidentReportData) {
            accidentReportFileList = accidentReportData.accidentReportFileList;
            initAccidentAreaId(accidentReportData.accidentAreaId);
            form.val("accidentReport-edit-form", {
                "reportId": accidentReportData.reportId,
                "tenantId": accidentReportData.tenantId,
                "accidentNo": accidentReportData.accidentNo,
                "accidentType": accidentReportData.accidentType,
                "accidentTitle": accidentReportData.accidentTitle,
                "accidentDate": accidentReportData.accidentDate,
                "accidentAreaId": accidentReportData.accidentAreaId,
                "accidentAreaName": accidentReportData.accidentAreaName,
                "accidentLevel": accidentReportData.accidentLevel,
                "noticeDeptFlg": accidentReportData.noticeDeptFlg,
                "noticeDeptName": accidentReportData.noticeDeptName,
                "noticeDeptDate": accidentReportData.noticeDeptDate,
                // "casualtyFlg": accidentReportData.casualtyFlg,
                "casualtyRemark": accidentReportData.casualtyRemark,
                "jobOperation": accidentReportData.jobOperation,
                "accidentShipType": accidentReportData.accidentShipType,
                "deptId": accidentReportData.deptId,
                "deptName": accidentReportData.deptName,
                "deptTeamId": accidentReportData.deptTeamId,
                "deptTeamName": accidentReportData.deptTeamName,
                "correlationUser": accidentReportData.correlationUser,
                "preliminarilyDamage": accidentReportData.preliminarilyDamage,
                "preliminarilyDescript": accidentReportData.preliminarilyDescript,
                "status": accidentReportData.status,
                "surveyStatus": accidentReportData.surveyStatus,
                "surveyDeadline": accidentReportData.surveyDeadline,
                "surveyDeptId": accidentReportData.surveyDeptId,
                "surveyDeptName": accidentReportData.surveyDeptName,
                "surveyUserId": accidentReportData.surveyUserId,
                "surveyUserName": accidentReportData.surveyUserName,
                "surveyRealName": accidentReportData.surveyRealName,
                "surveyUserNo": accidentReportData.surveyUserNo,
                "surveyRemark": accidentReportData.surveyRemark,
                "accidentElapse": accidentReportData.accidentElapse,
                "deathToll": accidentReportData.deathToll,
                "severeInjuryToll": accidentReportData.severeInjuryToll,
                "slightInjuryToll": accidentReportData.slightInjuryToll,
                "missingToll": accidentReportData.missingToll,
                "economyLoss": accidentReportData.economyLoss,
                "accidentOverview": accidentReportData.accidentOverview,
                "directReason": accidentReportData.directReason,
                "indirectionReason": accidentReportData.indirectionReason,
                "leaderUserId": accidentReportData.leaderUserId,
                "leaderUserName": accidentReportData.leaderUserName,
                "leaderUserNo": accidentReportData.leaderUserNo,
                "leaderRealName": accidentReportData.leaderRealName,
                "leaderDeptId": accidentReportData.leaderDeptId,
                "leaderDeptName": accidentReportData.leaderDeptName,
                "obligationRatio": accidentReportData.obligationRatio,
                "obligationCognizance": accidentReportData.obligationCognizance,
                "leaderDisposeCondition": accidentReportData.leaderDisposeCondition,
                "surveyAuditUserId": accidentReportData.surveyAuditUserId,
                "surveyAuditRealName": accidentReportData.surveyAuditRealName,
                "surveyAuditDate": accidentReportData.surveyAuditDate,
                "surveyAuditRemark": accidentReportData.surveyAuditRemark,
                "rectificationStatus": accidentReportData.rectificationStatus,
                "rectificationDeadline": accidentReportData.rectificationDeadline,
                "rectificationDeptId": accidentReportData.rectificationDeptId,
                "rectificationDeptName": accidentReportData.rectificationDeptName,
                "rectificationUserId": accidentReportData.rectificationUserId,
                "rectificationUserName": accidentReportData.rectificationUserName,
                "rectificationRealName": accidentReportData.rectificationRealName,
                "rectificationRemark": accidentReportData.rectificationRemark,
                "rectificationDate": accidentReportData.rectificationDate,
                "rectificationMeasures": accidentReportData.rectificationMeasures,
                "educationCondition": accidentReportData.educationCondition,
                "rectificationAuditUserId": accidentReportData.rectificationAuditUserId,
                "rectificationAuditRealName": accidentReportData.rectificationAuditRealName,
                "rectificationAuditDate": accidentReportData.rectificationAuditDate,
                "rectificationAuditRemark": accidentReportData.rectificationAuditRemark,
                "noticeChic": accidentReportData.noticeChic,
                "noticeDate": accidentReportData.noticeDate,
                "fileName": accidentReportData.fileName,
                "filePath": accidentReportData.fileName,
                "acceptAssistFlg": accidentReportData.acceptAssistFlg,
                "accidentPlace": accidentReportData.accidentPlace,
            });
            if(accidentReportData.noticeDeptFlg === '1'){
                $("#noticeDeptFlg").attr("checked","true");
                $("#noticeDeptDiv").show();
            }else{
                $("#noticeDeptFlg").removeAttr("checked");
                $("#noticeDeptDiv").hide();
            }
            // if(accidentReportData.casualtyFlg === '1'){
            //     $("#casualtyFlg").attr("checked","true");
            //     $("#casualtyDiv").show();
            // }else{
            //     $("#casualtyFlg").removeAttr("checked");
            //     $("#casualtyDiv").hide();
            // }
            if(accidentReportData.acceptAssistFlg === '1'){
                $("#acceptAssistFlg").attr("checked","true");
            }else{
                $("#acceptAssistFlg").removeAttr("checked");
            }
            // if(accidentReportData.correlationUser){
            //     let data = accidentReportData.correlationUser.split(',');
            //     let htl = ``;
            //     if (data && data.length > 0) {
            //         data.forEach((item, index) => {
            //             htl += `<span name="correlation" data-name="${item}" class="tag" >${item}<span style="color: red;margin-left: 5px;cursor:pointer;" onclick="delTags(this)">x</span></span>`
            //         })
            //     } else {
            //         htl += `<span name="correlation" data-name="${data}" class="tag" >${data}<span style="color: red;margin-left: 5px;cursor:pointer;" onclick="delTags(this)">x</span></span>`
            //     }
            //     $('.selectName').html(htl)
            // }
            form.render('checkbox');
        }
    }

    form.on('submit(accidentReport-edit-form-submit)', function (data) {
        data.field.status = '2';
        addOrUpdate(data.field,'提交');
        return false;
    });

    form.on('submit(accidentReport-edit-form-save)', function (data) {
        data.field.status = '1';
        addOrUpdate(data.field,'保存');
        return false;
    });

    // 状态 - 开关操作 报告主管部门
    form.on('switch(noticeDeptFlg)', function(data){
        var status = data.elem.checked;
        if(!status){
            $("#noticeDeptDiv").hide();
            $view.find('input[name="noticeDeptName"]').val("");
            $view.find('input[name="noticeDeptDate"]').val("");
            $view.find('input[name="noticeDeptName"]').attr("lay-verify","");
            $view.find('input[name="noticeDeptDate"]').attr("lay-verify","");
            $view.find('#noticeDeptName-label').removeClass("febs-form-item-require");
            $view.find('#noticeDeptDate-label').removeClass("febs-form-item-require");
        }else{
            $view.find('input[name="noticeDeptName"]').attr("lay-verify","required");
            $view.find('input[name="noticeDeptDate"]').attr("lay-verify","required");
            $view.find('#noticeDeptName-label').addClass("febs-form-item-require");
            $view.find('#noticeDeptDate-label').addClass("febs-form-item-require");
            $("#noticeDeptDiv").show();
        }
    });

    // 状态 - 开关操作 是否人员伤亡
    // form.on('switch(casualtyFlg)', function(data){
    //     var status = data.elem.checked;
    //     if(!status){
    //         $view.find('textarea[name="casualtyRemark"]').val("");
    //         $("#casualtyDiv").hide();
    //     }else{
    //         $("#casualtyDiv").show();
    //     }
    // });

    function initAccidentAreaId(projectId) {
        //初始化区域
        var data ={
            tenantId:tenantId,
            status:'1'
        };
        $("#accidentAreaId").empty();
        febs.getSync(ctx + 'baseArea', data, function (r) {
            var resultData = r.data;
            var options = '<option value="">请选择</option>';
            $.each(resultData, function (index, item) {
                options += '<option value="' + item.areaId + '">' + item.areaName + '</option>'
            })
            $("#accidentAreaId").append(options);
        });
    }
    
    function addOrUpdate(data,operation) {
        data.tenantId = tenantId;
        data.accidentReportFileList = getFileData();
        data.noticeDeptFlg = $noticeDeptFlg.is(':checked')?'1':'0';
        data.acceptAssistFlg = $acceptAssistFlg.is(':checked')?'1':'0';
        data.accidentAreaName = $("#accidentAreaId").find("option:selected").text().trim();
        //关联人员
        // let tagList =  $('.selectName').find('.tag');
        // if(tagList.length>0){
        //     let unameList = [];
        //     for (let i = 0; i < tagList.length; i++) {
        //         let name = $($(tagList)[i]).attr("data-name")
        //         unameList.push(name);
        //     }
        //     data.correlationUser = unameList.join(',');
        // }
        if (data.reportId && data.reportId.length > 0) {
            febs.modal.confirm(operation+'事故上报信息','确定'+operation+'事故上报信息？', function (index) {
                febs.postArray(ctx + 'accidentReport/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('修改成功');
                    $('#febs-accidentReport').find('#query').trigger('click');
                });
            });
        } else {
            febs.modal.confirm(operation+'事故上报信息','确定'+operation+'事故上报信息？', function (index) {
                febs.postArray(ctx + 'accidentReport', data, function () {
                    layer.closeAll();
                    febs.alert.success('新增成功');
                    $('#febs-accidentReport').find('#query').trigger('click');
                });
            });

        }
    }

    function getFileData(){
        var fileDatas = $view.find(".fileOne")
        var fileList = [];
        $.each(fileDatas,function (index, item){
            var data = {
                filePath: item.dataset.filepath,
                fileName: item.dataset.filename,
                smallPath: item.dataset.smallpath,
            }
            fileList.push(data);
        })
        return fileList;
    }

});